package com.servlet.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @Title: ServletUtils
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2023/12/22 15:40
 */
public class ServletUtils {

    private static ObjectMapper om = new ObjectMapper();

    static {
        //对象的所有字段全部列入
        om.setSerializationInclusion(JsonInclude.Include.ALWAYS);
//取消默认转换timestamps形式
        om.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//忽略空Bean转json的错误
        om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//所有的日期格式都统一转为为以下的样式，即yyyy-MM-dd HH:mm:ss
        om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//忽略 在json字符串中存在，但是在java对象中不存在对应属性的情况。防止错误
        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    public static void writeResponse(HttpServletResponse resp,ResponseVo responseVo) throws IOException {

        String s = om.writeValueAsString(responseVo);

        resp.setHeader("Content-Type", "application/json;charset=utf-8");
        resp.getWriter().write(s);

    }
}
